package com.syuson.biz.pay.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.springframework.util.StringUtils;

import com.syuson.filter.WebAppContextInitFilter;

/**
 * 
 * @author syuson
 *
 */
public class FileImageUtils {

	public static String uploadFile(InputStream inputStream, String oldpath) {
		String staticFileUploadDir = WebAppContextInitFilter.getInitedWebContextRealPath();

		String nameId = UUID.randomUUID().toString().replace("-", "");
		String path = "/upload/" + nameId;
		String fullPath = staticFileUploadDir + path;
		try {
			if (!StringUtils.isEmpty(oldpath)) {
				String oldPathParentFloder = oldpath.substring(0, path.lastIndexOf("/"));
				File oldFile = FileUtils.getFile(new String[] { staticFileUploadDir + oldPathParentFloder });
				FileUtils.deleteQuietly(oldFile);
			}
			FileUtils.copyInputStreamToFile(inputStream, new File(fullPath));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return path;
	}

	public static String generateRandomImage() {
		String staticFileUploadDir = WebAppContextInitFilter.getInitedWebContextRealPath();

		String nameId = UUID.randomUUID().toString().replace("-", "");
		String path = "/upload/" + nameId + ".png";
		String fullPath = staticFileUploadDir + path;
		return fullPath;
	}

	public static String staticFileUploadDir() {
		String staticFileUploadDir = WebAppContextInitFilter.getInitedWebContextRealPath();
		return staticFileUploadDir;
	}
}
